package com.fy.sys.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fy.core.dto.PageDto;
import com.fy.core.vo.ApiRest;
import com.fy.core.vo.PageResult;
import com.fy.sys.dto.RoleAddDto;
import com.fy.sys.entity.Role;
import com.fy.sys.entity.RoleMenu;
import com.fy.sys.mapper.RoleMapper;
import com.fy.sys.mapper.RoleMenuMapper;
import com.fy.sys.service.RoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author hxd
 * @since 2023-06-14
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Autowired
    private RoleMenuMapper roleMenuMapperl;
    @Override
    public PageResult<Role> pageFind(PageDto<Role> pageDto) {
        IPage<Role> page=new Page<>(pageDto.getNow(),pageDto.getSize());
        Role where=pageDto.getWhere();
        QueryWrapper<Role> roleQueryWrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(where.getRoleName())){
            roleQueryWrapper.lambda().like(Role::getRoleName,where.getRoleName());
        }
        if (!StringUtils.isEmpty(where.getRoleId())){
            roleQueryWrapper.lambda().like(Role::getRoleId,where.getRoleId());
        }
        if(!StringUtils.isEmpty(where.getRoleKey())){
            roleQueryWrapper.lambda().like(Role::getRoleKey,where.getRoleKey());
        }
        if (!StringUtils.isEmpty(where.getStatus())){
            roleQueryWrapper.lambda().eq(Role::getStatus,where.getStatus());
        }
        IPage<Role> pageInfo = this.baseMapper.selectPage(page, roleQueryWrapper);
        PageResult<Role> pageResult=new PageResult<>();
        pageResult.setPages(pageInfo.getPages());
        pageResult.setList(pageInfo.getRecords());
        pageResult.setTotal(pageInfo.getTotal());
        return pageResult;
    }

    @Override
    public ApiRest save(RoleAddDto roleAddDto) {
        //参数校验

        //保存role
        Role role = new Role();
        BeanUtil.copyProperties(roleAddDto,role,true);
        role.setDelFlag("0");
        role.setCreateBy("admin");
        role.setCreateTime(new Date());
        this.baseMapper.insert(role);
        //保存role_menu
        roleAddDto.getMenuIds().forEach(menuId -> {
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(role.getRoleId());
            roleMenu.setMenuId(menuId);
            roleMenuMapperl.insert(roleMenu);
        });
        return ApiRest.success("创建角色成功","");
    }
}
